#!/usr/bin/env bash

#
# Build php in WSL(RHEL)
#
# $ lnmp-wsl-php-builder.rhel 5.6.35 [--skipbuild] [tar] [rpm] [--ci]
#

_print_help_info(){

    echo "
Build php in WSL RHEL by shell script

Usage:

$ lnmp-wsl-builder-php-rhel 7.3.0 7.3.0beta3 7.3.0RC1 nightly

$ lnmp-wsl-builder-php-rhel [ yum | dnf | rpm | yum-devel | dnf-devel | rpm-devel ]

$ lnmp-wsl-builder-php-rhel 7.3.0 [ tar | rpm ] [--skipbuild] [--ci]

# echo \"--with-xxx --enable-xxx\" > /tmp/EXT_REAL_NAME.configure.options
$ lnmp-wsl-builder-php-rhel 7.3.0 enable-ext [EXT_NAME@EXT_REAL_NAME]
"

exit 0

}

################################################################################

_sudo(){
  command -v sudo > /dev/null && echo "sudo" || true
}

command -v yum > /dev/null

if ! [ $? -eq 0 ];then echo "Only Support RHEL"; exit; fi

################################################################################

PHP_TIMEZONE=PRC
PHP_URL=https://www.php.net/distributions
PHP_INSTALL_LOG=/tmp/php-builder/$(date +%s).install.log
PHP_GIT=https://github.com/php/php-src

if [ "${LNMP_CN_ENV}" != 'false' ];then
  PHP_URL=https://mirrors.sohu.com/php
  PHP_GIT=https://github.com.cnpmjs.org/php/php-src
fi

export COMPOSER_VERSION=2.0.8
export COMPOSER_ALLOW_SUPERUSER=1
export COMPOSER_HOME=/tmp/composer
export TZ=Asia/Shanghai
# export CC=clang CXX=clang
# export CC=gcc CXX=g++

################################################################################

#
# https://github.com/docker-library/php/issues/272
#

PHP_CFLAGS="-fstack-protector-strong -fpic -fpie -O2"
PHP_CPPFLAGS="$PHP_CFLAGS"
PHP_LDFLAGS="-Wl,-O1 -pie"

################################################################################

_get_phpnum(){

case "$1" in
  5.6.* )
    export PHP_NUM=56
    ;;

  7.0.* )
    export PHP_NUM=70
    ;;

  7.1.* )
    export PHP_NUM=71
    ;;

  7.2.* )
    export PHP_NUM=72
    ;;

  7.3.* )
    export PHP_NUM=73
    ;;

  7.4.* )
    export PHP_NUM=74
    ;;

  8.0.* )
    export PHP_NUM=80
    ;;

  8.1.* )
    export PHP_NUM=81
    export BUILD_FROM_GIT=1
    export PHP_SRC_BRANCH=PHP-8.1
    ;;

  nightly )
    export PHP_NUM=81
    export BUILD_FROM_GIT=1
    ;;

  * )
    echo "ONLY SUPPORT 5.6 7.0 7.1 7.2 7.3 7.4 8.0 nightly"
    exit 1
esac
}

################################################################################

_download_src(){
    $(_sudo) mkdir -p /usr/local/src
    $(_sudo) chmod -R 777 /usr/local/src

    if ! [ -z "$BUILD_FROM_GIT" ];then
      $(_sudo) yum install bison git -y

      git clone --depth=1 -b ${PHP_SRC_BRANCH:-master} \
      ${PHP_GIT} /usr/local/src/php-${PHP_VERSION} || \
        ( git -C /usr/local/src/php-${PHP_VERSION} fetch --depth=1 origin ${PHP_SRC_BRANCH:-master} ; \
          git -C /usr/local/src/php-${PHP_VERSION} reset --hard ${PHP_SRC_BRANCH:-master} ;
        )

      return
    fi

    if ! [ -d /usr/local/src/php-${PHP_VERSION} ];then

      echo -e "Download php src ...\n\n"

      cd /usr/local/src

      wget ${PHP_URL}/php-${PHP_VERSION}.tar.gz

      echo -e "Untar ...\n\n"

      tar -zxvf php-${PHP_VERSION}.tar.gz > /dev/null 2>&1
    fi
}

################################################################################

# 2. install packages

_install_php_run_dep(){

    cd /tmp

    if ! [ ${ID} = 'fedora' ];then
      $(_sudo) wget -N https://dl.fedoraproject.org/pub/epel/epel-release-latest-${VERSION_ID}.noarch.rpm

      $(_sudo) rpm -Uvh epel-release-latest-${VERSION_ID}.noarch.rpm
    fi

    # if [ ${VERSION_ID} -ge 8 -a ${ID} != 'fedora' ];then
    #   $(_sudo) wget -N https://rpms.remirepo.net/enterprise/remi-release-${VERSION_ID}.rpm
    #   $(_sudo) rpm -Uvh remi-release-${VERSION_ID}.rpm
    #   $(_sudo) dnf --enablerepo=remi install libtidy -y
    # fi

_libzip(){
    if [ ${ID} = 'fedora' ];then $(_sudo) dnf install -y libzip libzip-devel; return;fi
# libzip php7.2
#
# checking for libzip... configure: error: system libzip must be upgraded to version >= 0.11
#

    if [ ${VERSION_ID} -ge 8 ];then
      $(_sudo) dnf install -y pkgconf-pkg-config
      $(_sudo) dnf --repo AppStream install -y libzip libzip-devel

      return
    fi

    cd /tmp

    $(_sudo) wget -N http://packages.psychotic.ninja/7/plus/x86_64/RPMS/libzip-devel-0.11.2-6.el${VERSION_ID}.psychotic.x86_64.rpm

    $(_sudo) wget -N http://packages.psychotic.ninja/7/plus/x86_64/RPMS/libzip-0.11.2-6.el${VERSION_ID}.psychotic.x86_64.rpm

    $(_sudo) rpm -Uvh libzip*rpm ; cd -
}

    test ${PHP_NUM} -ge '72' && _libzip

    export PHP_DEP="libedit \
zlib \
libxml2 \
openssl \
libsqlite3x \
libxslt \
$(if [ ${VERSION_ID} -ge 8 -a ${ID} != 'fedora' ];then echo libcurl-minimal; else echo libcurl ;fi ) \
$(if [ ${VERSION_ID} -ge 8 ];then echo libpq; else echo postgresql-libs ;fi ) \
libmemcached \
cyrus-sasl \
freetype \
libpng \
libjpeg \
$( if [ $PHP_NUM -ge "72" ];then \
     echo $( if ! [ "${ARGON2}" = 'false' ];then \
               echo "libargon2";
             fi ); \
     echo "libsodium"; \
   fi ) \
libyaml \
bzip2 \
libexif \
gmp \
libc-client \
readline \
libicu \
libXpm \
libwebp \
enchant \
openldap \
aspell \
libffi \
krb5-libs \
oniguruma"

# $(if [ ${VERSION_ID} -ge 8 -a ${ID} != 'fedora' ];then true; else echo libtidy ;fi ) \

$(_sudo) yum install -y ${PHP_DEP} rpm-build > /dev/null
}

_install_php_build_dep(){

     export DEP_SOFTS="autoconf \
                   \
                   \
                   make \
                   \
                   re2c \
                   $( test ${CC:-gcc} = 'gcc'  && echo "gcc gcc-c++ libgcc" ) \
                   $( test "$CC" = 'clang'     && echo "clang" ) \
                   libedit-devel \
                   zlib-devel \
                   libxml2-devel \
                   openssl-devel \
                   libsqlite3x-devel \
                   libxslt-devel \
                   libcurl-devel \
                   $(if [ ${VERSION_ID} -ge 8 ];then echo libpq-devel; else echo postgresql-devel ;fi ) \
                   libmemcached-devel \
                   cyrus-sasl-devel \
                   freetype-devel \
                   libpng-devel \
                   libjpeg-devel \
                   \
                   $( test $PHP_NUM = "56" && echo "" ) \
                   $( test $PHP_NUM = "70" && echo "" ) \
                   $( test $PHP_NUM = "71" && echo "" ) \
                   $( if [ $PHP_NUM -ge "72" ];then \
                        echo $( if ! [ "${ARGON2}" = 'false' ];then \
                                  echo "libargon2-devel"; \
                                fi ); \
                        echo "libsodium-devel"; \
                      fi ) \
                      \
                   libyaml-devel \
                   bzip2-devel \
                   libexif-devel \
                   gmp-devel \
                   libc-client-devel \
                   readline-devel \
                   libicu-devel \
                   libXpm-devel \
                   \
                   libwebp-devel \
                   enchant-devel \
                   openldap-devel \
                   aspell-devel \
                   libffi-devel \
                   krb5-devel \
                   oniguruma-devel \
                   "
                  #  $(if [ ${VERSION_ID} -ge 8 -a ${ID} != 'fedora' ];then true; else echo libtidy-devel ;fi ) \

for soft in ${DEP_SOFTS}
do
    echo $soft | $(_sudo) tee -a ${PHP_INSTALL_LOG}
done

if [ $VERSION_ID -ge 8 -a ${ID} != 'fedora' ];then
  # $(_sudo) dnf --enablerepo=remi install libtidy-devel -y

  $(_sudo) dnf install -y dnf-utils
  $(_sudo) yum-config-manager --enable PowerTools
fi

$(_sudo) yum install -y ${DEP_SOFTS}
}

################################################################################

_test(){
    ${PHP_PREFIX}/bin/php -v

    $(_sudo) ln -sf ${PHP_PREFIX}/bin/php /usr/local/sbin/php

    ${PHP_PREFIX}/bin/composer --ansi --version --no-interaction || true ; $(_sudo) rm -rf /usr/local/sbin/php

    ${PHP_PREFIX}/bin/php -i | grep .ini

    ${PHP_PREFIX}/sbin/php-fpm -v

    set +x
    for ext in `ls /usr/local/src/php-${PHP_VERSION}/ext`; \
    do echo '*' $( ${PHP_PREFIX}/bin/php -r "if(extension_loaded('$ext')){echo '[x] $ext';}else{echo '[ ] $ext';}" ); done
    set -x
}

################################################################################

_builder(){

# 3. bug

# configure: error: Cannot find imap library (libc-client.a). Please check your c-client installation.
#
# https://blog.csdn.net/alexdream/article/details/7408453
#

     $(_sudo) ln -sf /usr/lib64/libc-client.so.2007 /usr/lib/libc-client.so

#
# configure: error: Cannot find ldap libraries in /usr/lib.
#
# @link https://blog.csdn.net/ei__nino/article/details/8598490

     $(_sudo) cp -frp /usr/lib64/libldap* /usr/lib/

# 4. configure

    CONFIGURE="--prefix=${PHP_PREFIX} \
        --sysconfdir=${PHP_INI_DIR} \
        \
        --build=${build:-x86_64-linux-gnu} \
        --host=${host:-x86_64-linux-gnu} \
        \
        --with-config-file-path=${PHP_INI_DIR} \
        --with-config-file-scan-dir=${PHP_INI_DIR}/conf.d \
        --enable-fpm --with-fpm-user=nginx --with-fpm-group=nginx \
        \
        --with-curl \
        --with-gettext \
        --with-kerberos \
        --with-libedit \
        --with-openssl \
          --with-system-ciphers \
        --with-pdo-mysql \
        --with-pdo-pgsql=shared \
        --with-xsl=shared \
        --with-zlib \
        --with-mhash \
        $( test $PHP_NUM -ge "74" && echo "--enable-gd=shared \
                                             --with-freetype \
                                             --with-jpeg \
                                             --with-webp \
                                             --with-xpm \
                                             --with-ffi=shared \
                                             --with-zip" \
        || echo "--with-pcre-regex \
                 --with-gd=shared \
                   --with-freetype-dir=/usr/lib \
                   --with-jpeg-dir=/usr/lib \
                   --with-png-dir=/usr/lib \
                   --with-xpm-dir=/usr/lib \
                   --enable-zip") \
            --disable-gd-jis-conv \
        --enable-ftp \
        --enable-mysqlnd \
        --enable-bcmath \
        --enable-mbstring \
        --enable-pcntl=shared \
        --enable-soap=shared \
        --enable-sockets=shared \
        --enable-sysvmsg=shared \
        --enable-sysvsem=shared \
        --enable-sysvshm=shared \
        --enable-calendar=shared \
        --enable-intl=shared \
        --enable-embed=shared \
        --enable-option-checking=fatal \
        --with-mysqli=shared \
        --with-pgsql=shared \
        \
        $( test $PHP_NUM = "56" && echo "--enable-opcache --enable-gd-native-ttf" ) \
        $( test $PHP_NUM = "70" && echo "--enable-gd-native-ttf --with-webp-dir=/usr/lib" ) \
        $( test $PHP_NUM = "71" && echo "--enable-gd-native-ttf --with-webp-dir=/usr/lib" ) \
       \
       $( if [ $PHP_NUM -ge "72" ];then \
         echo $( if ! [ "${ARGON2}" = 'false' ];then \
                   echo "--with-password-argon2"; \
                 fi ); \
         echo "--with-sodium --with-pcre-jit"; \
         if [ $PHP_NUM -lt "74" ];then \
           echo "--with-webp-dir=/usr/lib --with-libzip"; \
         fi; \
       fi ) \
        --enable-exif \
        --with-bz2 \
        --with-gmp \
        --with-imap=shared \
            --with-imap-ssl \
        \
        --with-pic \
        --with-enchant=shared \
        --enable-fileinfo=shared \
        --with-ldap=shared \
            --with-ldap-sasl \
        --with-pspell=shared \
        --enable-shmop=shared \
        "
        # --with-tidy \

    for item in ${CONFIGURE} ; do echo $item | $(_sudo) tee -a ${PHP_INSTALL_LOG}; done

    cd /usr/local/src/php-${PHP_VERSION}

    export CFLAGS="$PHP_CFLAGS"
    export CPPFLAGS="$PHP_CPPFLAGS"
    export LDFLAGS="$PHP_LDFLAGS"

    if ! [ -f configure ];then ./buildconf --force; fi

    ./configure ${CONFIGURE}

# 5. make

    make -j "$(nproc)"

    find -type f -name '*.a' -delete

# 6. make install

    $(_sudo) rm -rf ${PHP_PREFIX}

    if [ -d ${PHP_INI_DIR} ];then $(_sudo) mv ${PHP_INI_DIR} ${PHP_INI_DIR}.$( date +%s ).backup; fi

    $(_sudo) make install

################################################################################

    $(_sudo) mkdir -p ${PHP_INI_DIR}/conf.d

    $(_sudo) cp /usr/local/src/php-${PHP_VERSION}/php.ini-development ${PHP_INI_DIR}/php.ini
    $(_sudo) cp /usr/local/src/php-${PHP_VERSION}/php.ini-development ${PHP_INI_DIR}/php.ini-development
    $(_sudo) cp /usr/local/src/php-${PHP_VERSION}/php.ini-production  ${PHP_INI_DIR}/php.ini-production


# php5 not have php-fpm.d

    cd ${PHP_INI_DIR}

    if ! [ -d php-fpm.d ]; then
    # php5
        $(_sudo) mkdir php-fpm.d
        $(_sudo) cp php-fpm.conf.default php-fpm.d/www.conf

    { \
        echo '[global]'; \
        echo "include=${PHP_INI_DIR}/php-fpm.d/*.conf"; \
    } | $(_sudo) tee php-fpm.conf

    else
        $(_sudo) cp php-fpm.d/www.conf.default php-fpm.d/www.conf
        $(_sudo) cp php-fpm.conf.default php-fpm.conf
    fi

echo "
;;;;;;;;;;;;;;;;;;
; Global Options ;
;;;;;;;;;;;;;;;;;;

[global]

pid = /var/run/php${PHP_NUM}-fpm.pid

error_log = /var/log/php${PHP_NUM}-fpm.error.log

;;;;;;;;;;;;;;;;;;;;
; Pool Definitions ;
;;;;;;;;;;;;;;;;;;;;

[www]

access.log = /var/log/php${PHP_NUM}-fpm.access.log

user = nginx
group = nginx

request_slowlog_timeout = 5
slowlog = /var/log/php${PHP_NUM}-fpm.slow.log

clear_env = no

catch_workers_output = yes

; listen = 9000
; env[APP_ENV] = development

;
; wsl
;

; WSL1 not support listen ip:port
; listen = 127.0.0.1:9000

; WSL1 please use sock
listen = /var/run/php${PHP_NUM}-fpm.sock

listen.owner = nginx
listen.group = nginx
listen.mode = 0660

env[APP_ENV] = wsl

" | $(_sudo) tee ${PHP_INI_DIR}/php-fpm.d/zz-${ID}.conf

}

_install_pecl_ext_by_pickle(){
  export PATH=${PHP_PREFIX}/bin:$PATH
  $(_sudo) chmod 777 $(${PHP_PREFIX}/bin/php-config --extension-dir)

  if [ ${PHP_NUM} -ge "81" ];then set +e; fi

  PICKLE_OPTIONS="-n --php=${PHP_PREFIX}/bin/php -vvv"

  if [ $# -ne 0 ];then
    for extension in $@
    do
      local extension_real_name=$(echo $extension | cut -d "@" -f 2)
      local extension=$(echo $extension | cut -d "@" -f 1)

      $(_sudo) pickle install $extension ${PICKLE_OPTIONS} --defaults

      ${PHP_PREFIX}/bin/php -m > /dev/null 2>&1 \
        || $(_sudo) mv ${PHP_INI_DIR}/conf.d/php-ext-${extension_real_name}.ini \
                       ${PHP_INI_DIR}/conf.d/php-ext-${extension_real_name}.ini.notwork
    done

    $(_sudo) chmod 755 $(${PHP_PREFIX}/bin/php-config --extension-dir)
    set -e

    return
  fi

  echo "--enable-redis-igbinary" > /tmp/redis.configure.options
  echo "--enable-memcached-igbinary" > /tmp/memcached.configure.options

  if [ ${PHP_NUM} -ge "81" ];then
    _install_pecl_ext_by_pickle \
      https://github.com/igbinary/igbinary/archive/master.tar.gz@igbinary \
      https://github.com/phpredis/phpredis/archive/develop.tar.gz@redis \
      https://github.com/xdebug/xdebug/archive/master.tar.gz@xdebubg \
      https://github.com/tideways/php-xhprof-extension/archive/master.tar.gz@tideways_xhprof \
      https://github.com/swoole/swoole-src/archive/master.tar.gz@swoole \
      mongodb \
      memcached
  else
    $(_sudo) pickle install igbinary --defaults ${PICKLE_OPTIONS}
    $(_sudo) pickle install redis --defaults ${PICKLE_OPTIONS}
    $(_sudo) pickle install xdebug --defaults ${PICKLE_OPTIONS}
    $(_sudo) pickle install swoole --defaults ${PICKLE_OPTIONS}
    $(_sudo) pickle install memcached --defaults ${PICKLE_OPTIONS}
    $(_sudo) pickle install mongodb --defaults ${PICKLE_OPTIONS}
  fi

  $(_sudo) chmod 755 $(${PHP_PREFIX}/bin/php-config --extension-dir)
  set -e
}

_install_pecl_ext(){
    ${PHP_PREFIX}/bin/php-config | $(_sudo) tee -a ${PHP_INSTALL_LOG} || true

    command -v ${PHP_PREFIX}/bin/pecl && pecl=1 || pecl=0

    $(_sudo) mkdir -p /usr/local/sbin
    $(_sudo) ln -s ${PHP_PREFIX}/bin/php /usr/local/sbin
    $(_sudo) ln -s ${PHP_PREFIX}/bin/phpize /usr/local/sbin
    $(_sudo) ln -s ${PHP_PREFIX}/bin/php-config /usr/local/sbin

    if [ $pecl -eq 0 ];then
      _install_pecl_ext_by_pickle $@

      # $(_sudo) rm -rf /usr/local/sbin/{php,phpize,php-config}
      $(_sudo) rm -rf /usr/local/sbin/php*
      return
    fi

    #
    # https://github.com/docker-library/php/issues/443
    #

    $(_sudo) ${PHP_PREFIX}/bin/pecl update-channels

    PHP_EXTENSION="igbinary \
               redis \
               $( if [ $PHP_NUM = "56" ];then echo "memcached-2.2.0"; else echo "memcached"; fi ) \
               $( if [ $PHP_NUM = "56" ];then echo "xdebug-2.5.5"; else echo "xdebug"; fi ) \
               $( if [ $PHP_NUM = "56" ];then echo "yaml-1.3.1"; else echo "yaml"; fi ) \
               $( if ! [ $PHP_NUM = "56" ];then echo "swoole"; else echo ""; fi ) \
               mongodb"

    if [ $# -ne 0 ];then PHP_EXTENSION=$@;fi

    for extension in ${PHP_EXTENSION}
    do
        echo $extension | $(_sudo) tee -a ${PHP_INSTALL_LOG}
        $(_sudo) ${PHP_PREFIX}/bin/pecl install $extension || echo "install $extension error" | tee -a ${PHP_INSTALL_LOG}
    done

    $(_sudo) rm -rf /usr/local/sbin/php*
}

_php_ext_enable(){

echo "date.timezone=${PHP_TIMEZONE:-PRC}" | $(_sudo) tee ${PHP_INI_DIR}/conf.d/date_timezone.ini
echo "error_log=/var/log/php${PHP_NUM}.error.log" | $(_sudo) tee ${PHP_INI_DIR}/conf.d/error_log.ini
echo "session.save_path = \"/tmp\"" | $(_sudo) tee ${PHP_INI_DIR}/conf.d/session.ini

if [ $# -ne 0 ];then
  wsl-php-ext-enable.sh $@

  return
fi
set +e
exts=" pdo_pgsql \
                      xsl \
                      pcntl \
                      shmop \
                      soap \
                      sockets \
                      sysvmsg \
                      sysvsem \
                      sysvshm \
                      calendar \
                      fileinfo \
                      intl \
                      imap \
                      enchant \
                      ldap \
                      pspell \
                      \
                      mongodb \
                      igbinary \
                      redis \
                      memcached \
                      xdebug \
                      $( test $PHP_NUM != "56" && echo "swoole" ) \
                      opcache \
                      mysqli \
                      pgsql \
                      gd \
                      $( test $PHP_NUM -ge "74" && echo ffi )"

set -e
for ext in $exts
do
  wsl-php-ext-enable.sh $ext || echo "$ext install error" | tee -a ${PHP_INSTALL_LOG}
done

# config opcache

# echo 'opcache.enable_cli=1' | $(_sudo) tee -a ${PHP_INI_DIR}/conf.d/wsl-php-ext-opcache.ini
echo 'opcache.file_cache=/tmp' | $(_sudo) tee -a ${PHP_INI_DIR}/conf.d/wsl-php-ext-opcache.ini
}

_create_log_file(){
    cd /var/log

    if ! [ -f php${PHP_NUM}-fpm.error.log ];then $(_sudo) touch php${PHP_NUM}-fpm.error.log ; fi
    if ! [ -f php${PHP_NUM}-fpm.access.log ];then $(_sudo) touch php${PHP_NUM}-fpm.access.log ; fi
    if ! [ -f php${PHP_NUM}-fpm.slow.log ];then $(_sudo) touch php${PHP_NUM}-fpm.slow.log; fi

    $(_sudo) chmod 777 php${PHP_NUM}-*
}

_pickle(){
  # composer global require friendsofphp/pickle
  $(_sudo) curl -sfL -o /usr/local/bin/pickle \
    https://github.com/khs1994-php/pickle/releases/download/nightly/pickle-debug.phar
}

_composer(){
  $(_sudo) curl -sfL -o /usr/local/bin/composer \
    https://getcomposer.org/download/${COMPOSER_VERSION}/composer.phar
   # curl -sfL -o /tmp/installer.php \
   #     https://raw.githubusercontent.com/composer/getcomposer.org/cb19f2aa3aeaa2006c0cd69a7ef011eb31463067/web/installer
   #
   # ${PHP_PREFIX}/bin/php -r " \
   #      \$signature = '48e3236262b34d30969dca3c37281b3b4bbe3221bda826ac6a9a62d6444cdb0dcd0615698a5cbe587c3f0fe57a54d8f5'; \
   #      \$hash = hash('sha384', file_get_contents('/tmp/installer.php')); \
   #      if (!hash_equals(\$signature, \$hash)) { \
   #          unlink('/tmp/installer.php'); \
   #          echo 'Integrity check failed, installer is either corrupt or worse.' . PHP_EOL; \
   #          exit(1); \
   #      }" \
   #  && $(_sudo) ${PHP_PREFIX}/bin/php /tmp/installer.php --no-ansi --install-dir=${PHP_PREFIX}/bin --filename=composer --version=${COMPOSER_VERSION}
}

################################################################################

_write_version_to_file(){

echo "\`\`\`bash" | $(_sudo) tee -a ${PHP_PREFIX}/README.md

${PHP_PREFIX}/bin/php -v | $(_sudo) tee -a ${PHP_PREFIX}/README.md

echo "\`\`\`" | $(_sudo) tee -a ${PHP_PREFIX}/README.md

echo "\`\`\`bash" | $(_sudo) tee -a ${PHP_PREFIX}/README.md

${PHP_PREFIX}/bin/php -i | grep .ini | $(_sudo) tee -a ${PHP_PREFIX}/README.md

echo "\`\`\`" | $(_sudo) tee -a ${PHP_PREFIX}/README.md

echo "\`\`\`bash" | $(_sudo) tee -a ${PHP_PREFIX}/README.md

${PHP_PREFIX}/sbin/php-fpm -v | $(_sudo) tee -a ${PHP_PREFIX}/README.md

echo "\`\`\`" | $(_sudo) tee -a ${PHP_PREFIX}/README.md

echo "\`\`\`bash" | $(_sudo) tee -a ${PHP_PREFIX}/README.md

cat ${PHP_INSTALL_LOG} | $(_sudo) tee -a ${PHP_PREFIX}/README.md

echo "\`\`\`" | $(_sudo) tee -a ${PHP_PREFIX}/README.md

set +x

for ext in `ls /usr/local/src/php-${PHP_VERSION}/ext`; \
do echo '*' $( ${PHP_PREFIX}/bin/php -r "if(extension_loaded('$ext')){echo '[x] $ext';}else{echo '[ ] $ext';}" ) | $(_sudo) tee -a ${PHP_PREFIX}/README.md ; done

set -x

cat ${PHP_PREFIX}/README.md

}

################################################################################

_tar(){
  rm -rf /tmp/php${PHP_NUM}_ROOT/
  mkdir -p /tmp/php${PHP_NUM}_ROOT/etc

  cd /usr/local/

  cp -a php${PHP_NUM} /tmp/php${PHP_NUM}_ROOT/
  cp -a etc/php${PHP_NUM} /tmp/php${PHP_NUM}_ROOT/etc

  cd /tmp/php${PHP_NUM}_ROOT/

  $(_sudo) tar -zcvf /php${PHP_NUM}.tar.gz .
}

################################################################################

_rpm(){

PHP_PKG_VERSION=${PHP_VERSION}

test $PHP_VERSION = 'nightly' && PHP_PKG_VERSION=0.0.0 || true

cd /tmp

if [ ${ID} = 'fedora' ];then
  rpm_release_name="1.fc${VERSION_ID}"
else
  rpm_release_name="1.el${VERSION_ID}.centos"
fi

echo "Name:       khs1994-wsl-php${PHP_NUM}
Version:    ${PHP_PKG_VERSION}
Release:    ${rpm_release_name}
Summary:    PHP scripting language for creating dynamic web sites

License:    PHP and Zend and BSD
URL:        https://github.com/khs1994-docker/lnmp/tree/master/wsl

# BuildRequires:
Requires:   $( echo ${PHP_DEP} | sed "s# #, #g" )

%description
PHP is an HTML-embedded scripting language. PHP attempts to make it
easy for developers to write dynamically generated web pages. PHP also
offers built-in database integration for several commercial and
non-commercial database management systems, so writing a
database-enabled webpage with PHP is fairly simple. The most common
use of PHP coding is probably as a replacement for CGI scripts.
The php package contains the module (often referred to as mod_php)
which adds support for the PHP language to Apache HTTP Server.

%pre
if [ -d ${PHP_INI_DIR} ];then mv ${PHP_INI_DIR} ${PHP_INI_DIR}.\$( date +%s ).backup; fi
echo -e \"----------------------------------------------------------------------
\n
\n
Thanks for using khs1994-wsl-php${PHP_NUM} !\n
Please find the official documentation for khs1994-wsl-php${PHP_NUM} here:
* https://github.com/khs1994-docker/lnmp/tree/master/wsl\n
Meet issue? please see:
* https://github.com/khs1994-docker/lnmp/issues
\n
\n
----------------------------------------------------------------------
\n\n\"
%post
for file in \$( ls ${PHP_PREFIX}/bin ); do ln -sf ${PHP_PREFIX}/bin/\$file /usr/local/bin/ ; done
ln -sf ${PHP_PREFIX}/sbin/php-fpm /usr/local/sbin/
echo > /dev/null
cd /var/log
if ! [ -f php${PHP_NUM}.error.log ];then touch php${PHP_NUM}.error.log ; fi
if ! [ -f php${PHP_NUM}-fpm.error.log ];then touch php${PHP_NUM}-fpm.error.log ; fi
if ! [ -f php${PHP_NUM}-fpm.access.log ];then touch php${PHP_NUM}-fpm.access.log ; fi
if ! [ -f php${PHP_NUM}-fpm.slow.log ];then touch php${PHP_NUM}-fpm.slow.log; fi
chmod 777 php${PHP_NUM}*
%preun
echo
echo \"Meet issue? Please see https://github.com/khs1994-docker/lnmp/issues \"
echo
%build
%install
rm -rf %{buildroot}
ls -la %{buildroot}/../ || true
mkdir -p %{buildroot}
mkdir -p %{buildroot}/usr/local/etc
cp -a ${PHP_PREFIX} %{buildroot}/${PHP_PREFIX}
cp -a ${PHP_INI_DIR} %{buildroot}/${PHP_INI_DIR}
%files
%defattr (-,root,root,-)
${PHP_PREFIX}
${PHP_INI_DIR}
%changelog
%clean
RPM_NAME=khs1994-wsl-php${PHP_NUM}-%{version}-%{release}.x86_64.rpm
cp -a %{buildroot}/../../RPMS/x86_64/\${RPM_NAME} ~
" > khs1994-wsl-php${PHP_NUM}.spec

cat /tmp/khs1994-wsl-php${PHP_NUM}.spec

rpmbuild -bb /tmp/khs1994-wsl-php${PHP_NUM}.spec

RPM_NAME=khs1994-wsl-php${PHP_NUM}-${PHP_PKG_VERSION}-${rpm_release_name}.x86_64.rpm

echo "\$ yum install -y ${RPM_NAME}"

cp ~/${RPM_NAME} /

$(_sudo) rm -rf $PHP_PREFIX

$(_sudo) rm -rf $PHP_INI_DIR

$(_sudo) yum install -y /${RPM_NAME}

# test

_test
}

################################################################################

if [ -z "$1" ];then _print_help_info ; else PHP_VERSION="$1" ; fi

set -ex

command -v wget > /dev/null || $(_sudo) yum install -y wget

mkdir -p /tmp/php-builder

if [ "$PHP_VERSION" = 'rpm' -o "$PHP_VERSION" = 'yum' -o "$PHP_VERSION" = 'dnf' ];then \
    PHP_VERSION=7.4.13 ; fi

if [ "$PHP_VERSION" = 'rpm-devel' -o "$PHP_VERSION" = 'yum-devel' -o "$PHP_VERSION" = 'dnf-devel' ];then \
    PHP_VERSION=7.4.13 ; fi

_get_phpnum $PHP_VERSION

export PHP_PREFIX=/usr/local/php${PHP_NUM}

export PHP_INI_DIR=/usr/local/etc/php${PHP_NUM}

# verify os

. /etc/os-release

#
# ID="centos"
# VERSION_ID="7"
#
# ID=fedora
# VERSION_ID=27
#

$(_sudo) yum install -y libargon2-devel > /dev/null 2>&1 || export ARGON2=false

$(_sudo) yum install -y curl

command -v pickle > /dev/null || _pickle
command -v composer > /dev/null || _composer

$(_sudo) chmod +x /usr/local/bin/pickle /usr/local/bin/composer

if [ "$2" = 'enable-ext' ];then
   shift 2; \
   _test ; \
   _install_pecl_ext $@; \
   _php_ext_enable $@; \
   _create_log_file

   exit
fi

_install_php_run_dep

if [ "$1" = 'rpm' -o "$1" = 'yum' -o "$1" = 'dnf' ];then exit 0 ; fi
if [ "$1" = 'rpm-devel' -o "$1" = 'yum-devel' -o "$1" = 'dnf-devel' ];then _install_php_build_dep ; exit $? ; fi

_install_php_build_dep

for command in "$@"
do
  test $command = '--skipbuild' && export SKIP_BUILD=1
  test $command = '--ci'        && export PHP_URL=https://www.php.net/distributions
done

test "${SKIP_BUILD}" != 1 && ( \
  _download_src ; \
  _builder ; \
  _test ; \
  _install_pecl_ext ; \
  _php_ext_enable ; \
  _create_log_file ; \
  ${PHP_PREFIX}/bin/php-config | $(_sudo) tee -a ${PHP_INSTALL_LOG} || true ; \
  _write_version_to_file )

for command in "$@"
do
  test $command = 'tar' && _tar
  test $command = 'rpm' && _rpm
done

ls -lah /*.tar.gz /*.rpm || true
